<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
		<title>Meeting Bingo</title>
		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
		<script type="text/javascript" src="https://talkgadget.google.com/talkgadget/channel.js"></script>
		<script type="text/javascript" src="tgd/Services/Bingo/RESTClient.js"></script>
		<script type="text/javascript">
			//<![CDATA[

var tgd = tgd || {};
tgd.Buzzword = tgd.Buzzword || {};
tgd.Buzzword.GUI = tgd.Buzzword.GUI || {};
tgd.Buzzword.GUI.Panels = tgd.Buzzword.GUI.Panels || {};
tgd.Buzzword.GUI.Other = tgd.Buzzword.GUI.Other || {};
tgd.Buzzword.GUI.Buttons = tgd.Buzzword.GUI.Buttons || {};
tgd.Buzzword.GUI.GameStates = tgd.Buzzword.GUI.GameStates || { Ongoing : 1, Available : 2, Played : 3, Ended : 4 };
tgd.Buzzword.GUI.CurrentGame = null;

function init() {

	if (!window.localStorage.UserName) {
		var username = "";
		while(!(username = prompt("Please enter your username.")) || username === "") {}
		window.localStorage.UserName = username;
	}

	tgd.Buzzword.GUI.Panels.Available = document.getElementById("panAvailable");
	tgd.Buzzword.GUI.Panels.Create = document.getElementById("panCreate");
	tgd.Buzzword.GUI.Panels.Join = document.getElementById("panJoin");
	tgd.Buzzword.GUI.Panels.Details = document.getElementById("panDetails");
	tgd.Buzzword.GUI.Panels.Play = document.getElementById("panPlay");
	tgd.Buzzword.GUI.Panels.Loading = document.getElementById("panLoading");
	tgd.Buzzword.GUI.Panels.OngoingGames = document.getElementById("panOngoingGames");
	tgd.Buzzword.GUI.Panels.AvailableGames = document.getElementById("panAvailableGames");
	tgd.Buzzword.GUI.Panels.PlayedGames = document.getElementById("panPlayedGames");
	tgd.Buzzword.GUI.Panels.EndedGames = document.getElementById("panEndedGames");
	tgd.Buzzword.GUI.Panels.OngoingGamesRepeater = document.getElementById("panOngoingGamesRepeater");
	tgd.Buzzword.GUI.Panels.AvailableGamesRepeater = document.getElementById("panAvailableGamesRepeater");
	tgd.Buzzword.GUI.Panels.PlayedGamesRepeater = document.getElementById("panPlayedGamesRepeater");
	tgd.Buzzword.GUI.Panels.EndedGamesRepeater = document.getElementById("panEndedGamesRepeater");
	tgd.Buzzword.GUI.Panels.Feed = document.getElementById("panFeed");

	tgd.Buzzword.GUI.Other.GameTitle = document.getElementById("lblGameTitle");
	tgd.Buzzword.GUI.Other.DetailGameTitle = document.getElementById("lblDetailGameTitle");
	tgd.Buzzword.GUI.Other.JoinGameTitle = document.getElementById("lblJoinGameTitle");
	tgd.Buzzword.GUI.Other.DetailsBackButton = document.getElementById("lnkDetailsBackButton");

	tgd.Buzzword.GUI.Buttons.Join = document.getElementById("btnJoin");

	setPanel(tgd.Buzzword.GUI.Panels.Available);

	tgd.Buzzword.Game = new tgd.Services.Bingo.RESTClient();
	
    //get game from URL
    if (window.location.search.search(/game=/) > -1) {
        joinGame(window.location.search.substr(window.location.search.search(/game=/) + 5));
    } else {
	    getGames();
    }
}

function getGames() {
	setLoading(true);
	tgd.Buzzword.Game.getGames(
		window.localStorage.UserName,
		function(data) {
			tgd.Buzzword.GUI.Panels.OngoingGamesRepeater.textContent =
				tgd.Buzzword.GUI.Panels.AvailableGamesRepeater.textContent =
				tgd.Buzzword.GUI.Panels.PlayedGamesRepeater.textContent =
				tgd.Buzzword.GUI.Panels.EndedGamesRepeater.textContent = "";

			for (var i = 0; i < data.Games.length; ++i) {
				var game = data.Games[i];

				//TODO put ENDED and AVAILABLE in a static enum in RESTClient
				if (game.Status === "ENDED") {  //ENDED
					if (game.Joined) {  //PLAYED
						row = rowFactory(tgd.Buzzword.GUI.GameStates.Played, game);
						tgd.Buzzword.GUI.Panels.PlayedGamesRepeater.appendChild(row);
						showElement(tgd.Buzzword.GUI.Panels.PlayedGames);
					} else {  //ENDED
						row = rowFactory(tgd.Buzzword.GUI.GameStates.Ended, game);
						tgd.Buzzword.GUI.Panels.EndedGamesRepeater.appendChild(row);
						showElement(tgd.Buzzword.GUI.Panels.EndedGames);
					}
				} else if (game.Joined) {  //ONGOING
					row = rowFactory(tgd.Buzzword.GUI.GameStates.Ongoing, game);
					tgd.Buzzword.GUI.Panels.OngoingGamesRepeater.appendChild(row);
					showElement(tgd.Buzzword.GUI.Panels.OngoingGames);
				} else {  //AVAILABLE
					row = rowFactory(tgd.Buzzword.GUI.GameStates.Available, game);
					tgd.Buzzword.GUI.Panels.AvailableGamesRepeater.appendChild(row);
					showElement(tgd.Buzzword.GUI.Panels.AvailableGames);
				}
			}
			setLoading(false);
			getToken(window.localStorage.UserName);
		}
	);
}

function getWords(game) {
	setLoading(true);
	tgd.Buzzword.GUI.Panels.Play.getElementsByClassName("repeater")[0].textContent = "";

	tgd.Buzzword.Game.getWords(
		game,
		window.localStorage.UserName,
		function(data) {
			var repeater = tgd.Buzzword.GUI.Panels.Play.getElementsByClassName("repeater")[0];
			var rowTemplate = document.getElementById("templates").getElementsByClassName("panAvailableGames")[0];

			for (var i = 0; i < data.Words.length; ++i) {
				var div = rowTemplate.cloneNode(true);
				var btn = div.getElementsByClassName("btnJoin")[0];
				var lbl = div.getElementsByClassName("gameName")[0];
				btn.textContent = "+";
				lbl.Word = btn.Word = data.Words[i];
				btn.onclick = function(event) {
					incrementWord(tgd.Buzzword.GUI.CurrentGame.ID, event.target.Word.ID);
				}
				lbl.textContent = data.Words[i].Word + "  [" + data.Words[i].Count + "]";
				repeater.appendChild(div);
			}

			//todo:  only game creator should see this
			var div = rowTemplate.cloneNode(true);
			var btn = div.getElementsByClassName("btnJoin")[0];
			btn.textContent = "End";
			btn.onclick = function(event) {
				if (confirm("Are you sure you want to end this game?")) {
					endGame(tgd.Buzzword.GUI.CurrentGame.ID);
					setPanel(tgd.Buzzword.GUI.Panels.Available);
				}
			}
			div.getElementsByClassName("gameName")[0].textContent = "End this game?";
			repeater.appendChild(div);

			setLoading(false);
		}
	);
}

function incrementWord(game, word) {
	setLoading(true);
	tgd.Buzzword.Game.incrementWord(
		game,
		word,
		function(data) {
			var repeater = tgd.Buzzword.GUI.Panels.Play.getElementsByClassName("repeater")[0];

			for (var i = 0; i < repeater.childNodes.length; ++i) {
				if (repeater.childNodes[i].getElementsByClassName("btnJoin")[0].Word.ID === data.ID) {
					repeater.childNodes[i].getElementsByClassName("gameName")[0].textContent = data.Word + "  [" + data.Count + "]";
					break;
				}
			}
			setLoading(false);
		}
	);
}

function addGame() {
	setLoading(true);
	var txtGame = document.getElementById("txtGame");
	tgd.Buzzword.Game.createGame(
		txtGame.value,
		window.localStorage.UserName, 
		function(data) {
			newRow = rowFactory(tgd.Buzzword.GUI.GameStates.Available, data);
			tgd.Buzzword.GUI.Panels.AvailableGamesRepeater.appendChild(newRow);
			showElement(tgd.Buzzword.GUI.Panels.AvailableGames);
			txtGame.value = "";
			setLoading(false);
            alert(window.location.protocol + "//" + window.location.hostname + window.location.pathname + "?game=" + data.ID);
		}
	);
}

function joinGame(game) {
	setLoading(true);

	tgd.Buzzword.Game.joinGame(
		game,
		window.localStorage.UserName,
		function(data) {
			var newRow = rowFactory(tgd.Buzzword.GUI.GameStates.Available, data);

			tgd.Buzzword.GUI.Panels.AvailableGamesRepeater.appendChild(newRow);
			showElement(tgd.Buzzword.GUI.Panels.AvailableGames);

			setLoading(false);
			getToken(window.localStorage.UserName);
		}
	);
}

function setWords(game) {
	setLoading(true);
	var words = [];
	var inputs = tgd.Buzzword.GUI.Panels.Join.getElementsByTagName("input");

	for (var i = 0; i < inputs.length; ++i) {
		if (inputs[i].type === "text") {
			words.push(inputs[i].value);
		}
	}

	tgd.Buzzword.Game.setWords(
		game,
		window.localStorage.UserName,
		words.join(","),
		function(data) {
            var row = getGameRow(data.ID);
			var newRow = rowFactory(tgd.Buzzword.GUI.GameStates.Ongoing, data);

			tgd.Buzzword.GUI.Panels.AvailableGamesRepeater.removeChild(row)

			if (tgd.Buzzword.GUI.Panels.AvailableGamesRepeater.childNodes.length === 0) {
				hideElement(tgd.Buzzword.GUI.Panels.AvailableGames);
			}

			tgd.Buzzword.GUI.Panels.OngoingGamesRepeater.appendChild(newRow);
			showElement(tgd.Buzzword.GUI.Panels.OngoingGames);

			setLoading(false);
		}
	);
}

function getGameData(game) {
	setLoading(true);
	tgd.Buzzword.GUI.Panels.Details.getElementsByClassName("repeater")[0].textContent = "";

	tgd.Buzzword.Game.getGameData(
		game,
		function(data) {
			tgd.Buzzword.GUI.Other.DetailGameTitle.textContent = data.Name;
			var repeater = tgd.Buzzword.GUI.Panels.Details.getElementsByClassName("repeater")[0];
			var rowTemplate = document.getElementById("templates").getElementsByClassName("panAvailableGames")[0];

			for (var i = 0; i < data.Users.length; ++i) {
				var div = rowTemplate.cloneNode(true);
				hideElement(div.getElementsByClassName("btnJoin")[0]);
				div.getElementsByClassName("gameName")[0].textContent = data.Users[i].Name + "  [" + data.Users[i].Score + "]";
				repeater.appendChild(div);
			}

			if (data.CreatedBy === window.localStorage.UserName) {
				var div = rowTemplate.cloneNode(true);
				var btn = div.getElementsByClassName("btnJoin")[0];
				btn.textContent = "Delete";
				btn.onclick = function(event) {
					if (confirm("Are you sure you want to delete this game?")) {
						deleteGame(tgd.Buzzword.GUI.CurrentGame.ID);
						setPanel(tgd.Buzzword.GUI.Panels.Available);
					}
				}
				div.getElementsByClassName("gameName")[0].textContent = "Delete this game?";
				repeater.appendChild(div);
			}

			setLoading(false);
		}
	);
}

function renameGame(game, name) {
	setLoading(true);
	tgd.Buzzword.Game.updateGame(
		game,
		{ Name : name },
		function(data) {
			var row = getGameRow(data.ID);
			row.getElementsByClassName("gameName")[0].textContent = data.Name;
			setLoading(false);
		}
	);
}

function endGame(game) {
	setLoading(true);
	tgd.Buzzword.Game.updateGame(
		game,
		{ Status : "ENDED" },
		function(data) {
			var row = getGameRow(data.ID);
			//TODO: for now, assuming that to end a game you had to of joined it
			var newRow = rowFactory(tgd.Buzzword.GUI.GameStates.Played, tgd.Buzzword.GUI.CurrentGame);
			tgd.Buzzword.GUI.Panels.OngoingGamesRepeater.removeChild(row);

			if (tgd.Buzzword.GUI.Panels.OngoingGamesRepeater.childNodes.length === 0) {
				hideElement(tgd.Buzzword.GUI.Panels.OngoingGames);
			}

			tgd.Buzzword.GUI.Panels.PlayedGamesRepeater.appendChild(newRow);
			showElement(tgd.Buzzword.GUI.Panels.PlayedGames);

			setLoading(false);
		}
	);
}

function deleteGame(game) {
	setLoading(true);

	tgd.Buzzword.Game.updateGame(
		game,
		{ Delete : true },
		function(data) {
			var row = getGameRow(data.ID);

			if (row.parentNode.childNodes.length === 1) {
				hideElement(row.parentNode.parentNode);
			}

			row.parentNode.removeChild(row);

			setLoading(false);
		}
	);
}

function getToken(user) {
	setLoading(true);
	tgd.Buzzword.Game.getToken(
		user,
		function(data) {
			var chan = new goog.appengine.Channel(data.Token);

			var socket = chan.open( {
				onopen : function() { console.log("socket opened"); },
				onmessage : function(msg) {
					$("#panFeed").prepend("<div class='listRow'>" + msg.data + "</div>");
				},
				onerror : function(err) { console.log(err.description); },
				onclose : function() { console.log("socket closed") }
			});

			setLoading(false);
		}
	);
}

function rowFactory(type, game) {
	var row = document.getElementById("templates").getElementsByClassName("panAvailableGames")[0].cloneNode(true);
	var btn = row.getElementsByClassName("btnJoin")[0];
	var lbl = row.getElementsByClassName("gameName")[0];
	row.Game = btn.Game = lbl.Game = game;
	lbl.textContent = game.Name;
	lbl.onclick = function(event) {
		var newName;
		if ((newName = prompt("Enter a new name for the game.", event.target.Game.Name)) && newName !== "" && newName !== event.target.Game.Name) {
			renameGame(event.target.Game.ID, newName);
		}
	}

	switch (type) {
		case tgd.Buzzword.GUI.GameStates.Ongoing : {
			btn.onclick = function(event) {
				tgd.Buzzword.GUI.CurrentGame = event.target.Game;
				getWords(tgd.Buzzword.GUI.CurrentGame.ID);
				tgd.Buzzword.GUI.Other.GameTitle.textContent = tgd.Buzzword.GUI.CurrentGame.Name;
				setPanel(tgd.Buzzword.GUI.Panels.Play);
			}
			break;
		}
		case tgd.Buzzword.GUI.GameStates.Available : {
			btn.onclick = function(event) {
				tgd.Buzzword.GUI.CurrentGame = event.target.Game;
				tgd.Buzzword.GUI.Other.JoinGameTitle.textContent = tgd.Buzzword.GUI.CurrentGame.Name;
				setPanel(tgd.Buzzword.GUI.Panels.Join);
			}
			break;
		}
		case tgd.Buzzword.GUI.GameStates.Played :
		case tgd.Buzzword.GUI.GameStates.Ended : {
			btn.onclick = function(event) {
				tgd.Buzzword.GUI.CurrentGame = event.target.Game;
				tgd.Buzzword.GUI.Other.DetailsBackButton.href = "javascript:(function(){setPanel(tgd.Buzzword.GUI.Panels.Available);})()";
				getGameData(event.target.Game.ID);
				setPanel(tgd.Buzzword.GUI.Panels.Details);
			}
			break;
		}
		default: throw new Error("Invalid type specified.");
	}

	return row;
}

function getGameRow(id) {
	var row;

	for (var i = 0; i < tgd.Buzzword.GUI.Panels.OngoingGamesRepeater.childNodes.length; ++i) {
		if (tgd.Buzzword.GUI.Panels.OngoingGamesRepeater.childNodes[i].Game.ID === id) {
			row = tgd.Buzzword.GUI.Panels.OngoingGamesRepeater.childNodes[i];
			return row;
		}
	}

	for (var i = 0; i < tgd.Buzzword.GUI.Panels.AvailableGamesRepeater.childNodes.length; ++i) {
		if (tgd.Buzzword.GUI.Panels.AvailableGamesRepeater.childNodes[i].Game.ID === id) {
			row = tgd.Buzzword.GUI.Panels.AvailableGamesRepeater.childNodes[i];
			return row;
		}
	}

	for (var i = 0; i < tgd.Buzzword.GUI.Panels.PlayedGamesRepeater.childNodes.length; ++i) {
		if (tgd.Buzzword.GUI.Panels.PlayedGamesRepeater.childNodes[i].Game.ID === id) {
			row = tgd.Buzzword.GUI.Panels.PlayedGamesRepeater.childNodes[i];
			return row;
		}
	}

	for (var i = 0; i < tgd.Buzzword.GUI.Panels.EndedGamesRepeater.childNodes.length; ++i) {
		if (tgd.Buzzword.GUI.Panels.EndedGamesRepeater.childNodes[i].Game.ID === id) {
			row = tgd.Buzzword.GUI.Panels.EndedGamesRepeater.childNodes[i];
			return row;
		}
	}
}

function setLoading(show) {
	if (show) {
	    showElement(tgd.Buzzword.GUI.Panels.Loading);
	} else {
	    hideElement(tgd.Buzzword.GUI.Panels.Loading);
	}
}

function setPanel(pan) {
    hideElement(tgd.Buzzword.GUI.Panels.Available);
    hideElement(tgd.Buzzword.GUI.Panels.Create);
    hideElement(tgd.Buzzword.GUI.Panels.Join);
    hideElement(tgd.Buzzword.GUI.Panels.Details);
    hideElement(tgd.Buzzword.GUI.Panels.Play);

    showElement(pan);
}

function hideElement(ele) {
    if (ele.className.search("hidden") < 0) {
	    ele.className = ele.className.concat(" hidden");
	}
}

function showElement(ele) {
	if (ele.className.search("hidden") >= 0) {
	    ele.className = ele.className.replace("hidden", "");
	}
}

			//]]>
		</script>

		<style type="text/css">
			body,html{margin:0;height:100%;width:100%;background:#fff;font-family:sans-serif;}

			h1{background:#D9E2FA;color:#249;padding:7px 0;margin:0;text-align:center;position:relative;font-size:1em;border-bottom:1px solid #93aded;}
			h1 a{text-decoration:none;color:#249;padding:5px 15px;border:solid 1px #9EADD2;background:#EBEFF9;}
			h1 a.right,h1 a.left{position:absolute;top:1px;}
			h1 a.right{right:5px;}
			h1 a.left{left:5px;}

			h2{background:#EBEFF9;color:#249;border-top:solid 1px #ccc;border-bottom:solid 1px #a9b7d7;padding:7px 0;margin:0;font-size:1em;font-weight:normal;}

			.listRow{position:relative;color:#333;border-bottom:solid 1px #eee;border-top:solid 1px #ccc;overflow:hidden;padding: 7px 5px;}
			.listRow div{}
			.listRow input,
			.listRow .button{margin:0;padding:0 5px;color:#249;font-weight:bold;font-family:consolas,monospace;font-size:1em;text-decoration:none;border:solid 1px #93aded;background:#fff;}
			.listRow .button{padding:5px 15px;}
			.listRow span.button{border:none;}
			.listRow .right,.listRow .left{position:absolute;top:1px;}
			.listRow .right{right:5px;}
			.listRow .left{left:5px;}

			.hidden{display:none;}

			#templates{display:none;}
		</style>
	</head>
	<body id="body" onload="init();">
		<div id="content">
			<div id="panAvailable" class="hidden">
				<h1>
					<a href="javascript:(function() { getGames(); } )()">Games</a>
					<a href="javascript:(function() { setPanel(tgd.Buzzword.GUI.Panels.Create); } )()" type="button" class="button right">+</a>
				</h1>
				<div id="panOngoingGames" class="hidden">
					<h2>Ongoing</h2>
					<div id="panOngoingGamesRepeater" class="libRepeater repeater"></div>
				</div>
				<div id="panAvailableGames" class="hidden">
					<h2>Available</h2>
					<div id="panAvailableGamesRepeater" class="libRepeater repeater"></div>
				</div>
				<div id="panPlayedGames" class="hidden">
					<h2>Played</h2>
					<div id="panPlayedGamesRepeater" class="libRepeater repeater"></div>
				</div>
				<div id="panEndedGames" class="hidden">
					<h2>Ended</h2>
					<div id="panEndedGamesRepeater" class="libRepeater repeater"></div>
				</div>
			</div>

			<div id="panCreate" class="hidden">
				<h1>
					<a class="left" href="javascript:(function(){setPanel(tgd.Buzzword.GUI.Panels.Available);})()">&laquo;</a>
					New
				</h1>
				<div>
					<div class="listRow">
						<label>Name: </label>
						<input type="text" id="txtGame" size="20" maxlength="20" />
					</div>
					<div class="listRow">
						<input type="button" class="button" value="Create" onclick="addGame();setPanel(tgd.Buzzword.GUI.Panels.Available);" />
					</div>
				</div>
			</div>

			<div id="panJoin" class="hidden">
				<h1>
					<a class="left" href="javascript:(function(){setPanel(tgd.Buzzword.GUI.Panels.Available);})()">&laquo;</a>
					<span id="lblJoinGameTitle"></span>
				</h1>
				<div>
					<div class="listRow">
						<input type="text" size="20" maxlength="20" />
					</div>
					<div class="listRow">
						<input type="text" size="20" maxlength="20" />
					</div>
					<div class="listRow">
						<input type="text" size="20" maxlength="20" />
					</div>
					<div class="listRow">
						<input type="text" size="20" maxlength="20" />
					</div>
					<div class="listRow">
						<input type="text" size="20" maxlength="20" />
					</div>
					<div class="listRow">
						<input type="button" id="btnJoin" class="button" value="Join" onclick="setWords(tgd.Buzzword.GUI.CurrentGame.ID);setPanel(tgd.Buzzword.GUI.Panels.Available);" />
					</div>
				</div>
			</div>

			<div id="panDetails" class="hidden">
				<h1>
					<a id="lnkDetailsBackButton" class="left">&laquo;</a>
					<a id="lblDetailGameTitle" href="javascript:(function() { getGameData(tgd.Buzzword.GUI.CurrentGame.ID); } )()"></a>
				</h1>
				<div class="libRepeater repeater"></div>
			</div>

			<div id="panPlay" class="hidden">
				<h1>
					<a class="left" href="javascript:(function(){setPanel(tgd.Buzzword.GUI.Panels.Available);})()">&laquo;</a>
					<a id="lblGameTitle" href="javascript:(function() { getWords(tgd.Buzzword.GUI.CurrentGame.ID); } )()"></a>
					<a href="javascript:(function() { tgd.Buzzword.GUI.Other.DetailsBackButton.href = 'javascript:(function(){setPanel(tgd.Buzzword.GUI.Panels.Play);})()'; setPanel(tgd.Buzzword.GUI.Panels.Details); getGameData(tgd.Buzzword.GUI.CurrentGame.ID); } )()" type="button" class="button right">&hellip;</a>
				</h1>
				<div class="libRepeater repeater"></div>
			</div>
		</div>

		<div id="panFeed">
            <a href="http://meetingbingo.appspot.com/_ah/login_redir?claimid=www.google.com/accounts/o8/id&continue=http://dl.dropbox.com/u/8941568/oojs/Buzzword.htm">sign in</a>
		</div>

		<div id="templates">
			<!-- genericize this template, used for available, joined, play -->
			<div class="panAvailableGames listRow">
				<div class="gameName"></div>
				<span class="btnJoin button right" >&raquo;</span>
			</div>
		</div>

		<div id="panLoading" class="hidden" style="position: fixed; top: 0pt; bottom: 0pt; right: 0pt; left: 0pt;">
			<div style="position: fixed; top: 0pt; bottom: 0pt; left: 0pt; right: 0pt; background: none repeat scroll 0% 0% rgb(0, 0, 0); opacity: 0.8;"></div>
			<div style="position: fixed; top: 0pt; right: 0pt; left: 0pt; bottom: 0pt; text-align: center; padding-top: 5em;">
				<span onclick="setLoading(false);" style="border:1px solid #9eadd2;padding: 5px 15px; color:#249; background: #ebeff9; font-size: 2em;">loading ...</span>
			</div>
		</div>
	</body>
</html>
